<!--组织架构-->
<template>
  <div class="execution">
    <div class="top-box">
      <span>单位名称：</span>
      <el-input v-model="input" placeholder="请输入内容" class="in"></el-input>
      <el-button class="ma btn" size="small" type="primary" @click="onSearchDepart()">查询</el-button>
      <el-button size="small" type="warning" @click="resetForm()">重置</el-button>
    </div>
    <basic-container>
      <div class="avue-crud">
        <!--新增单位及弹窗-->
<!--        <el-button ref="addOrUpdate" class="xz" size="small" type="success" @click="addTreeselect()">新 增</el-button>-->
        <el-dialog :title="dialogTitle" :visible.sync="visible" :close-on-click-modal="false" ref="dataFrom" center width="636px">
          <el-form :model="form" :rules="rules">
            <!--上级单位-->
            <el-form-item prop="parentId" label="上级单位" :label-width="formLabelWidth">
              <treeselect v-model="form.parentId"
                          :options="menuOptions"
                          :show-count="true"
                          :normalizer="normalizer"
                          :disabled="disable"
                          class="in"
                          placeholder="选择上级菜单">
              </treeselect>
            </el-form-item>
            <!--单位名称-->
            <el-form-item prop="name" label="单位名称" :label-width="formLabelWidth">
              <el-input v-model.trim="form.name" autocomplete="off" placehoder="填写单位名称" class="in" prop="name"></el-input>
            </el-form-item>
            <!--单位状态-->
            <el-form-item prop="typeNum" label="单位类型" :label-width="formLabelWidth">
                <el-radio v-model="form.typeNum" label="1">单位</el-radio>
                <el-radio v-model="form.typeNum" label="2">年级</el-radio>
              <el-radio v-model="form.typeNum" label="3">班级</el-radio>
            </el-form-item>
          </el-form>
          <!--是否保存-->
          <div slot="footer" class="dialog-footer">
            <el-button @click="visible = false">取 消</el-button>
            <el-button type="primary" @click="Submit()">确 定</el-button>
          </div>
        </el-dialog>
        <!--列表-->
        <el-table
            stripe
            border
            v-loading="loading"
            ref="topicTable"
            :data=menuList
            :cell-style="tableCellStyle"
            :header-cell-style='tableHeaderColor'
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            :expand-row-keys="['0']"
            row-key="len">
          <el-table-column prop="name" label="单位名称" :show-overflow-tooltip="true" style="text-align: left" ></el-table-column>
<!--          <el-table-column prop="isLock" label="是否有权限" align="center">-->
<!--            <template slot-scope="scope">-->
<!--              <el-tag type="success"  v-if="scope.row.isLock === false">有权限</el-tag>-->
<!--              <el-tag type="danger"  v-if="scope.row.isLock === true">无权限</el-tag>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column align="center" label="创建时间" prop="createTime"></el-table-column>
          <el-table-column align="center" label="修改时间" prop="updateTime">
            <template slot-scope="scope">
              <span v-if="scope.row.updateTime == null"> 无 </span>
              <span v-else>{{scope.row.updateTime}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="修改操作人" prop="operator">
            <template slot-scope="scope">
              <span v-if="scope.row.operator == null"> 未修改 </span>
              <span v-else>{{scope.row.operator}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="operation" label="操作" align="center" class-name="small-padding fixed-wdeptidth" width="250px">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="revise(scope.row)">编辑</el-button>
              <el-button size="mini" type="success" @click="addTreeselect(scope.row,scope.row.id)">新增</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)" :disabled="scope.row.parentId == 0">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </basic-container>
  </div>
</template>

<script>
import {addObj, delObj, departObj, editObj, reviseObj, SearchObj,departList} from '@/api/depart/department'
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"

export default {
  name: "depart",
  components: {Treeselect},
  data() {
    return {
      rowIndex:'',
      company:'',
      total:null,
      // 遮罩层
      loading: true,
      // 菜单表格树数据
      menuList: [],
      newMenuList:[],
      // 菜单树选项
      menuOptions: [],
      treeselect:[],
      //搜索框
      input: '',
      name:'',
      //弹窗
      visible:false,
      //标题
      dialogTitle:'',
      //定义表单内容
      form: {
        id: null,
        menuId: '',
        name: '',
        isLock: '',
        createTime: '',
        typeNum: '',
      },
      disable:'',
      //弹窗内容宽度
      formLabelWidth: '120px',
      //表格样式
      tableCellStyle: {
        'font-size': '16px',
        'padding': '14px 0',
        'color': '#000',
      },
      //表头样式
      tableHeaderColor: {
        'font-size': '16px',
        'padding': '14px 0',
        'font-weight': 'normal',
        'color': '#000',
        'text-align': 'center',
      },
      checked1: true,
      // 表单校验
      rules: {
        parentId: [
          {required: true}
        ],
        name: [
          {required: true, trigger: "none"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //展示表格
    getList() {
      this.loading = true;
      let param = {
        'current':this.currentPage,
      }
      departObj(param).then(res => {
        this.total=res.data.data.total;
        // 2021/8/4  根据数据权限本级及子级修改组织架构的反参处理  将平级过滤掉无权限的，然后处理成树状
        let arr1 = res.data.data
        let arr = arr1.filter(item => item.isLock != true )
         //找到parentId最小的为最外层父级
        let a = Math.min.apply(Math, arr.map((item, index) => {
          return item.parentId
        }))
        let b = Math.min.apply(Math, arr.map((item, index) => {
          this.$set(item, 'len')
          item.len = index
          return index
        }))

        //根节点
        function transTreeData(items){
          if(items.length>0){
            var curPid = a //pid=0，为最上层节点 ，即无父节点
            var parent=findChild(curPid);//数组
            return parent;
          }else{
            return [];
          }
        }

        //子节点
        function findChild (curPid){
          var _arr = [];
          var items= arr;
          var length=items.length;
          for(var i = 0; i < length; i++){
            if(items[i].parentId == curPid){
              var _obj = items[i];
              _obj.children = findChild(_obj.id);
              _arr.push(_obj);
            }
          }
          return _arr;
        }
        this.menuList = transTreeData(arr)
        // function add(){
        //   arr.forEach(item =>{
        //     // if(item.parentId !== 0){
        //       arr.forEach(itemson=>{
        //         if(itemson.parentId === item.id){
        //           const newarr = []
        //           var obj = item.children
        //           item.children.push(itemson)
        //           newarr.push(obj)
        //           // if (itemson.children) {
        //           //   //如果该item 还存在children节点  把当前的item项当做父节点进行递归
        //           //   // console.log(item, "子节点中仍然存在children节点")
        //           //   const newarr = []
        //           //   newarr.push(itemson)
        //             console.log(newarr)
        //           //   return add(newarr)
        //           // }
        //         }
        //       })
        //     // }
        //   })
        // }

        // function getGrade(arr) {
          // let lv1 = getLv1(arr) // 1. 先将一级菜单获取到，放到一个数组里边
          // newArr = addSon(lv1)
          // function addSon(arr) {
          //   arr.forEach((item) => {
          //     if (item.parentId !== 0) {
          //       arr.forEach((lv1Item) => {
          //         if (item.parentId === lv1Item.id) {
          //           lv1Item.children.push(item)
          //           if (item.children) {
          //             //如果该item 还存在children节点  把当前的item项当做父节点进行递归
          //             // console.log(item, "子节点中仍然存在children节点")
          //             const newarr = []
          //             newarr.push(item)
          //             return addSon(newarr)
          //           }
          //         }
          //       })
          //     }
          //   })
          //   // return lv1
          // }
        // this.menuList = res.data.data
        this.loading = false;
      });
    },

    //删除
    handleDelete(row) {
      this.$confirm('是否删除单位"' + row.name + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal:false,
      }).then(function () {
        return delObj(row.id);
      }).then(() => {
        this.getList();
        this.$message.success('删除成功')
      })
    },


    // 搜索
    onSearchDepart:function() {
      if (this.input == "") {
        this.$message.warning("查询条件不能为空！");
      }else{
        let param = {
          'name':this.input,
          'deptTypeNum': [1]
        };
        SearchObj(param).then(res => {
          this.menuList = res.data.data
        });
      }
    },

    // 重置
    resetForm:function() {
      this.input = null
      let param = {
        'name': this.input,
      };
      departObj(param).then(res => {
        this.menuList = res.data.data
        this.getList(this.page)
      });
    },

    /** 查询菜单下拉树结构 */
    addTreeselect(row,id) {
      this.rowIndex = row
      this.visible = true;
      this.dialogTitle="新增单位";
      if (id != null){
        this.form.parentId = id;
        this.disable=true;
        this.form.name = null
        this.form.isLock = null
        this.form.typeNum = null
        departObj().then(res => {
          this.menuOptions = [];
          const menu = {id: 0, name: '学校',children: []};
          menu.children = res.data.data;
          this.menuOptions.push(menu);
        });
      }else{
        this.disable=false
        departList().then(res => {
          this.menuOptions = [];
          const menu = {id: 0, name: '学校', children: []};
          menu.children = res.data.data[0].children;
          this.menuOptions.push(menu);
        });
        this.form.parentId = null
        this.form.name = null
        this.form.isLock = null
        this.form.typeNum = null
      }
    },

    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      //无权限的删除子节点
      if(node.isLock === true){
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },

    //根据ID查询
    revise(row) {
      this.visible = true;
      this.dialogTitle="编辑";
      this.disable=true
      reviseObj(row.id).then(res => {
        this.form = res.data.data
        departObj().then(res => {
          this.menuOptions = [];
          const menu = {id: 0, name: '学校', children: []};
          menu.children = res.data.data;
          this.menuOptions.push(menu);
        });
      });
    },

    //新增表单提交
    Submit(){
      // debugger
      this.loading = true;
      let param = {
        'parentId': this.form.parentId,
        'name': this.form.name,
        'isLock': this.form.isLock,
        'typeNum': this.form.typeNum,
        'sort': 1
      }
      if (this.form.deptId == null) {
        addObj(param).then(res => {
          this.getList();
          this.visible = false;
          this.loading = false;
          this.$message.success('添加成功')
          this.$refs.topicTable.toggleRowExpansion(this.rowIndex, true)
          this.form.parentId = null
          this.form.name = null
          this.form.isLock = null
          this.form.typeNum = null
        });
        this.loading = false;
      }else
      {
        editObj(this.form).then(res => {
          this.getList();
          this.visible = false;
          this.loading = false;
          this.$message.success('修改成功')
          this.form.deptId = null
          this.form.parentId = null
          this.form.name = null
          this.form.isLock = null
          this.form.typeNum = null
        });
        this.loading = false;
      }
    },
  }
};
</script>
<style scoped>
.top-box{
  width: 505px;
  height: 60px;
  border: 1px solid #DCDFE6;
  border-radius: 10px;
  padding: 12px 0 12px 20px;
  background:#fff;
  margin: 20px 0 30px 40px;
}
.in{
  width: 40% !important;
  height: 35px !important;
  line-height: 35px !important;
}
.xz{
  margin-bottom: 20px;
}
.ma{
  margin-left: 20px;
}
.xzdw{
  font-weight: bold;
  margin-left: 50px;
  padding-bottom: 20px;
}
.option{
  margin-left: 70px;
}

</style>
<style>
.el-dialog__header{
  font-weight: bold;
  margin-left: 25px;
  text-align: left;
  padding: 28px 0 10px 0;
}
.vue-treeselect--disabled .vue-treeselect__control {
  background-color: #f1f1f1;
}
</style>
